package com.dycong.common.network;

import com.dycong.common.function.TryToDo;
import lombok.Data;

import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by yu on 16-3-25.
 */
public interface RichStateHttpClient {

    RichStateHttpClientImpl.Result doGet(String url, String encoding, Map<String, String> header, Map<String, String> body);

    RichStateHttpClientImpl.Result doPost(String url, String encoding, Map<String, String> headerMap, Map<String, String> paramMap);

    RichStateHttpClientImpl.Result postJson(String url, String encoding, Map<String, String> headerMap, String json);

    default RichStateHttpClientImpl.Result doGet(String url, String encoding) {
        return doGet(url, encoding, null, null);
    }

    default RichStateHttpClientImpl.Result doPost(String url, String encoding) {
        return doPost(url, encoding, null, null);
    }

    default RichStateHttpClientImpl.Result postJson(String url, String encoding, String json) {
        return postJson(url, encoding, null, json);
    }


    @Data
    class Result {
        String content;
        int statusCode;
        Map<String, List<String>> responseHeader;
    }


    static String encodeQueryString(Map<String, String> map, String encoding) {
        return map.entrySet()
                .stream()
                .map(e -> e.getKey() + "=" + TryToDo.tryToGet(() -> URLEncoder.encode(e.getValue(), encoding)).orElseThrow(() -> new RuntimeException("unknown encoding: " + encoding)))
                .collect(Collectors.joining("&"));
    }
}
